#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <unistd.h>
#include <cstring>
#include <cstdio>
using std::cout;
using std::cin;
using std::endl;

class TCP_Client
{
    public:
    TCP_Client(std::string ip,int port):sock_(-1),ip_(ip),port_(port){}
    ~TCP_Client()
    {
        if(sock_ >= 0)
        close(sock_);
    }
    bool Client_Init()
    {
        
        sock_=socket(AF_INET,SOCK_STREAM,0);
        if(sock_ < 0)
        {
            cout<<"Create TCP_Client Socket Failed"<<endl;
            return false;
        }
        return true;
    }
    void Request()
    {
        char buffer[1024];
        std::string msg;
        while(1)
        {
            cout<<"Please Enter # ";
            getline(std::cin,msg);
            msg+="\r";
            write(sock_,msg.c_str(),msg.size());
            ssize_t size=read(sock_,buffer,sizeof(buffer)-1);
            if(size > 0)
            {
                buffer[size]='\0';
                cout<<"["<<"Echo String"<<"] say#"<<buffer<<endl;
            }
            else if(size == 0)
            {
                cout<<"Server Close Sock_fd"<<endl;
                break;
            }
            else
            {
                perror("read Server failed");
                return ;
            }
        }
    }
    bool Client_Start()
    {
        struct sockaddr_in peer;
        memset(&peer,0,sizeof(peer));
        peer.sin_family=AF_INET;
        peer.sin_port=htons(port_);
        peer.sin_addr.s_addr=inet_addr(ip_.c_str());
        if(connect(sock_,(struct sockaddr*)&peer,sizeof(peer)) != 0)
        {
            cout<<"Connect TCP_Client Socket Failed"<<endl;
            return false;
        }
        else
        {
            cout<<"Connect TCP_Client Socket Successed"<<endl;
            Request();
        }
        cout<<"Connect will closed"<<endl;
        return true;
    }
    private:
    int sock_;
    std::string ip_;
    int port_;
};